﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.IO;
using System.Configuration;
using WebUI.Models;
using WebUI.Util;
using System;
using System.Net;

namespace WebUI.Controllers
{
    public class MappingFileController : Controller
    {
        public ActionResult Index(Periodicity? periodicity = null, string processName = null, string responsible = null, string resultDate = null, 
                string status = null, bool todayProcess = false)
        {
            resultDate = string.IsNullOrEmpty(resultDate) ? DateTime.Today.ToString("yyyyMMdd") : resultDate;

            try
            {
                var xmlPath = ConfigurationManager.AppSettings["XmlPathResults"];
                var filePath = string.Format(ConfigurationManager.AppSettings.Get("XmlPathResults").ToString(), resultDate);
                var models = XmlHelper.DeserializeFromXml<List<Models.MappingFileModel>>(filePath);

                var modelsFiltered = models.Where(x => (periodicity == null || x.Periodicy == periodicity.ToString())
                    && (processName == null || processName == "All" || x.ProcessName == processName)
                    && (responsible == null || responsible == "All" || x.Responsible == responsible)
                    && (todayProcess == false || x.DeadLine.Date == DateTime.Today)
                    && (status == null || status == "All" || ((int)x.Status).ToString() == status))
                    .OrderBy(x => x.Periodicy).ThenBy(x => x.ProcessName).ThenBy(x => x.SubProcessName).ToList();

                ViewBag.LastUpdate = System.IO.File.GetLastWriteTime(filePath);

                FillViewBag(models, processName, responsible, resultDate, status, todayProcess);

                return View(modelsFiltered);
            }
            catch
            {
                FillViewBag(new List<MappingFileModel>(), processName, responsible, resultDate);
                return View(new List<MappingFileModel>());
            }
        }

        private void FillViewBag(IEnumerable<MappingFileModel> processes, string processSelected = null, string responsibleSelected = null,
            string resultDate = null, string statusSelected = null, bool todayProcess= false)
        {
            var selectItems = processes.Select(x => x.ProcessName).Distinct().OrderBy(x => x).Select(process => new SelectListItem
            {
                Text = process,
                Value = process,
                Selected = process == processSelected
            }).ToList();

            selectItems.Insert(0, new SelectListItem { Text = "All", Value = null, Selected = processSelected == null });
            ViewBag.Processes = selectItems;
            ViewBag.ProcessSelected = processSelected;

            var selectItemsResponsible = processes.Select(x => x.Responsible).Distinct().OrderBy(x => x).Select(responsible => new SelectListItem
            {
                Text = responsible,
                Value = responsible.Normalize(),
                Selected = responsible.Normalize() == responsibleSelected
            }).ToList();

            selectItemsResponsible.Insert(0, new SelectListItem { Text = "All", Value = null, Selected = responsibleSelected == null });
            ViewBag.Responsibles = selectItemsResponsible;
            ViewBag.ResponsibleSelected = responsibleSelected;

            ViewBag.ResultDate = resultDate;

            var selectItemsStatus = new List<SelectListItem>{ 
                new SelectListItem { Text = "All", Value = null, Selected = responsibleSelected == null },
                new SelectListItem { Text = "Executed", Value = "0", Selected = statusSelected == "0" },
                new SelectListItem { Text = "Executed (Not Validated)", Value = "1", Selected = statusSelected == "1" },
                new SelectListItem { Text = "Executed (Late)", Value = "2", Selected = statusSelected == "2" },
                new SelectListItem { Text = "Failed", Value = "3", Selected = statusSelected == "3" },
                new SelectListItem { Text = "Not Processed", Value = "4", Selected = statusSelected == "4" }
            };
            ViewBag.Status = selectItemsStatus;
            ViewBag.StatusSelected = statusSelected;

            ViewBag.TodayProcess = todayProcess;
        }

        private static void SetStatusAndDate(bool hasOutFileXml, ProcessModel item, MappingFileModel model, bool existsFileControl, bool existsOutFile)
        {
            if (!existsFileControl && !existsOutFile)
                model.Status = Status.Waiting;

            if (existsFileControl && hasOutFileXml && !existsOutFile)
                model.Status = Status.Failed;

            if (existsFileControl && hasOutFileXml && existsOutFile)
                model.Status = Status.Executed;

            //if (existsFileControl && !hasOutFileXml)
            //    model.Status = Status.ExecutedNotValidate;

            var createdTime = hasOutFileXml && existsOutFile
                ? System.IO.File.GetCreationTime(item.OutFile) : existsFileControl
                ? System.IO.File.GetCreationTime(item.ControlFile) : DateTime.MinValue;

            //if (createdTime.AddYears(-createdTime.Year + 1).AddMonths(-createdTime.Month + 1).AddDays(-createdTime.Day + 1) >
            //    item.EndTime && (existsOutFile || existsFileControl))
            //    model.Status = Status.ExecutedAfterTime;

            model.ExecutedAt = createdTime;
        }
    }
}
